package test_achieve;

import constant.Constant;
import cucumber.api.Scenario;
import lombok.Data;
import org.openqa.selenium.By;
import util.JdbcUtil;
import util.tools.CommonTools;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chenkuo on 2018/5/23.
 */
@Data
public class DataStatistics {

    /**
     * 数据统计计算机mac地址
     */
    public void addMachineID() {
//        Constant.machineID.add("F8-28-19-E5-2E-0k");
//        Constant.machineID.add("18-5E-0F-17-C0-32");
//        Constant.machineID.add("F8-28-19-E4-F2-CF");
//        Constant.machineID.add("70-1C-E7-FE-23-CE");
//        Constant.machineID.add("F8-28-19-DE-FA-B5");
//        Constant.machineID.add("F8-28-19-E5-2E-0D");
        Constant.machineID.add("F8-28-19-E5-2E-01");
    }

    /**
     * 是否为第一次运行
     * Constant.isFirstRun = 1 第一次运行
     * Constant.isFirstRun = 2 非第一次运行
     */
    public static int isFirstRun() {
        for (int i = 0; i < Constant.runParms.size(); i++) {
            System.out.println("所有的参数："+Constant.runParms.get(i));
            String runParms = Constant.runParms.get(i);
            if (runParms.equals("@target/rerun.txt")) {
                Constant.isFirstRun = 2;
            }else {
                Constant.isFirstRun = 1;
            }

        }

        return Constant.isFirstRun;
    }

    /**
     * 获取jenkins的环境变量
     */
    public String getJenkinsEnv(String keyName) {

        Map<String, String> envs = System.getenv();
        for (String key : envs.keySet()) {
//            envs.get(key);
            System.out.println(key + "=" + envs.get(key));
            return envs.get(keyName);
        }
        return "abc";
    }
    /**
     * 传入你个list去掉@符合
     */
    public String delefuhao(String testModules){
        String adc = null;
        String[] modules= testModules.split(",");
        System.out.println(modules.length);
        for (int i = 0; i < modules.length; i++) {
            if (modules[i].contains("@")){
                modules[i] = CommonTools.cutEnd(modules[i],"@");
            }
            adc= modules[i]+","+adc;
        }
        return  CommonTools.cutFront(adc,",null");
    }

    public static void main(String[] args) {
        DataStatistics de = new DataStatistics();
        String a = de.delefuhao("报错,@bcd");
        System.out.println(a);
    }
    /**
     * 测试模块特殊显示处理
     */
    public String getTrueModule(){
        String testModule = null;
        for (int i = 0; i < Constant.runParms.size(); i++) {
            if (Constant.runParms.get(i).contains("@")) {
                String parms = Constant.runParms.get(i);
                System.out.println("需要处理参数："+parms);
                parms=CommonTools.cutEnd(parms,"@");
                if (parms.equals("todo")||parms.equals("null")){

                }else{
                    testModule = parms + "," + testModule;

                }

            }
        }
        return delefuhao( CommonTools.cutFront(testModule,",null"));
    }

    /**
     * 获取测试模块名称或服务名称
     */
    public String getTestModule() {
        String jobName = getJenkinsEnv("JOB_NAME");//jenkins任务名称
        String buildID = getJenkinsEnv("BUILD_ID");//构建序号
        int build = Integer.valueOf(buildID) - 1;//上次构建id

        if (Constant.isFirstRun == 1) {
            Constant.testModule =getTrueModule();
        } else {
            //拿到上次构建的场景名称
            String sql = "SELECT module_name FROM itest.u_auto_result WHERE jenkins_name ='" + jobName + "' AND jenkins_id = " + build + "";
//            System.out.println("拿到上次构建的场景名称:"+sql);
            Constant.testModule = JdbcUtil.sqlStringReportExecute(sql);
        }

        return Constant.testModule;
    }

    /**
     * 测试结果：1成功 2失败
     */
    public int getTestResult() {
        Constant.testResult = 1;
        if (Constant.failCaseNum > 1) {
            Constant.testResult = 2;
        }
        return Constant.testResult;
    }

    /**
     * 设置测试报告地址
     */
    public void setHtmlReport() {
        String jobName = getJenkinsEnv("JOB_NAME");//jenkins任务名称
        String buildID = getJenkinsEnv("BUILD_ID");//构建序号
        Constant.htmlReport = "http://172.33.0.5:8081/jenkins/view/autotest/job/" + jobName + "/" + buildID + "/cucumber-html-reports/overview-features.html";
    }

    /**
     * 生成任务ID
     */
    public String getTestID() {
        String testID = null;
        if (isFirstRun() == 1) {
            UUID uuid = UUID.randomUUID();
            System.out.println(uuid);
            return uuid.toString();
        } else {
            String jobName = getJenkinsEnv("JOB_NAME");//jenkins任务名称
            int buildID = Integer.valueOf(getJenkinsEnv("BUILD_ID"))-1;//构建序号
            //根据当前的buildID减去1获取上次的buildID，并根据这个查找到上一次的任务ID并返回。

            String sql = "SELECT task_id FROM itest.u_auto_result WHERE jenkins_name ='" + jobName + "' AND jenkins_id = " + buildID + "";
//            System.out.println("拿到上次构建的task_id:"+sql);
            testID = JdbcUtil.sqlStringReportExecute(sql);
        }
        return testID;
    }

    public void dataStatistics() throws UnknownHostException {
        addMachineID();
        InetAddress localhost = InetAddress.getLocalHost();
        Date now = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowstr = df.format(now);
        int isFirstRun = isFirstRun(); //是否为第一次运行：1：第一次 2：第二次
        String jobName = getJenkinsEnv("JOB_NAME");//jenkins任务名称
        String buildID = getJenkinsEnv("BUILD_ID");//构建序号
        String moduleName = getTestModule();//测试模块名称
        String visitName = Constant.allCaseName.toString();//运行的所有场景名称
        String vistaRunFailName = Constant.failCaseName.toString();//所有失败场景名称
        String machineIp = localhost.getHostAddress();//执行机器ip地址
        int runResult = getTestResult(); //1：成功；2：失败
        int runStatus = 2; //1：有效；2：无效
        String htmlReport = "http://172.33.0.5:8081/jenkins/view/autotest/job/" + jobName + "/" + buildID + "/cucumber-html-reports/overview-features.html";
        System.out.println("测试报告:" + htmlReport);
        String createTime = nowstr;
        System.out.println("createTime:" + nowstr);
        String operator = "小明";//执行人
        int vistaRunCounts = Constant.allCaseNum;//执行数量
        int vistaFailCounts = Constant.failCaseNum;//失败场景数量
        int vistaSuccessCounts = Constant.passCaseNum;//通过场景数量
        String taskId = getTestID();//得到任务ID
        String machine = CommonTools.getLocalMac();//当前机器的mac地址

        for (int i = 0; i < Constant.machineID.size(); i++) {
            if (machine.equals(Constant.machineID.get(i))) {
                String sql = "insert itest.u_auto_result(jenkins_name,jenkins_id,evn,module_name,visit_name,vista_run_fail_name,machine_ip,run_result,run_status," +
                        "html_report,create_time,operator,vista_run_counts,vista_fail_counts,vista_success_counts,is_first_run,task_id) values ('" + jobName + "'," + buildID + ",'"+Constant.evn+"','" + moduleName + "','" + visitName + "','" + vistaRunFailName + "','" + machineIp + "',"
                        + runResult + "," + runStatus + ",'" + htmlReport + "','" + createTime + "','" + operator + "'," + vistaRunCounts + "," + vistaFailCounts + "," + vistaSuccessCounts + "," + isFirstRun + ",'" + taskId + "')";
                System.out.println(sql);
                JdbcUtil.sqlReportExecute(sql);
            } else {
//                System.out.println("MAC地址不匹配，不往数据库中统计，本机mac地址："+machine);
            }
        }
    }

//    private void dataStatisti1cs(Scenario scenario) throws IOException {
////        addMachineID();
//        Map<String, String> envs = System.getenv();
//        for (String key : envs.keySet()) {
//            System.out.println(key + "=" + envs.get(key));
//        }
//        String jobName = envs.get("JOB_NAME");//jenkins任务名称
//        String buildID = envs.get("BUILD_ID");//构建序号
//        String machine = CommonTools.getLocalMac();//当前机器的mac地址
//        InetAddress localhost = InetAddress.getLocalHost();
//        String featureName = CommonTools.cutMiddle(scenario.getUri(), "feature/", ".feature");//场景名称
//        boolean isScenario = scenario.isFailed();//场景执行结果
//        String machine_ip = localhost.getHostAddress();//执行机器ip地址
//        int result = isScenario == true ? 2 : 1;//执行结果
//        int status = 1;//是否有效
//        String html_report = "http://172.33.0.5:8081/jenkins/view/autotest/job/" + jobName + "/" + buildID + "/cucumber-html-reports/overview-features.html";
//        Date now = new Date();
//        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String nowstr = df.format(now);
//        String create_time = nowstr;
//        String operator = "阿强";//执行人员
//        for (int i = 0; i < Constant.machineID.size(); i++) {
//            if (machine.equals(Constant.machineID.get(i))) {
//                String sql = "insert itest.u_simple_result(visit_name,machine_ip,result,status," +
//                        "html_report,create_time,operator) values ('" + featureName + "','" + machine_ip + "',"
//                        + result + "," + status + ",'" + html_report + "','" + create_time + "','" + operator + "')";
//                JdbcUtil.sqlReportExecute(sql);
//            } else {
////                System.out.println("MAC地址不匹配，不往数据库中统计，本机mac地址："+machine);
//            }
//        }
//
//    }


}
